# Gathers all deck files on disk and creates a popup menu for the player
# To select one to load.
class_name DeckLoader
extends MenuButton

# This signal carries the chosen deck contents in a dictionary.
signal deck_loaded(deck)
# This value temporary holds all discovered decks form the disk
# between looking at the decks to load, and selecting one.
var _load_decks_list := []

func _ready() -> void:
	# warning-ignore:return_value_discarded
	get_popup().connect("index_pressed", self, "_on_deck_load")
	# warning-ignore:return_value_discarded
	connect("about_to_show", self, "_on_about_to_show")


# Returns an Array of Dictionaries, where each dictionary is the details
# of a deck loaded from disk.
static func load_all_decks() -> Array:
	var available_decks = CFUtils.list_files_in_directory(CFConst.DECKS_PATH)
	var file = File.new()
	var loaded_decks_list := []
	for deck in available_decks:
		file.open(CFConst.DECKS_PATH + deck, File.READ)
		var data = JSON.parse(file.get_as_text())
		file.close()
		# We expect decks in JSON Dictionary format
		# In the future we might support plaintext as well.
		if typeof(data.result) == TYPE_DICTIONARY:
			loaded_decks_list.append(data.result)
	return(loaded_decks_list)


# Triggered just after pressing the Load button.
# Populates the menu options with one entry per available deck to load
# from the decks that exist in CFConst.DECKS_PATH
func _on_about_to_show() -> void:
	# We need to clear the choices generated by previous presses.
	get_popup().clear()
	_load_decks_list = load_all_decks()
	# Each file has the dictionary ready to go for our choices list
	# We format each choice label, to show some relevant info about each deck
	for deck in _load_decks_list:
		get_popup().add_item(
				deck.name + ' (' + str(deck.total) + ' cards)')
	if get_popup().get_item_count() == 0:
		get_popup().add_item("No decks found. Please create a deck and try again")


# Triggered when a deck has been chosen from the popup menu.
# Emits a signal with the deck contents.
func _on_deck_load(index: int) -> void:
	# Since our temp deck list is an array, we can match the index of the
	# menu choice, with the index in the array
	if _load_decks_list.size():
		var deck = _load_decks_list[index]
		emit_signal("deck_loaded",deck)
